<?php

namespace App\Http\Controllers\AdminApi;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Exception;

class FileController extends BaseController
{
    public function initialize(Request $request)
    {
        parent::initialize($request);

        $this->modelName = 'File';
    }

    /**
     * List
     */
    public function list(Request $request)
    {
        $param = $request->all();

        $page = 1;
        $limit = 20;
        if (!empty($param['page'])) {
            $page = (int)$param['page'];
        }
        if (!empty($param['limit'])) {
            $limit = (int)$param['limit'];
        }
        $page = ($page - 1) * $limit;
        $sort_field = $param['sort_field'] ?? '';
        $sort_value = $param['sort_value'] ?? '';

        $className = '\\App\\Models\\' . $this->modelName;
        $model = new $className;
        $field = $this->defaultField;
        $orders = $this->defaultOrder;
        $where = $this->getFilterWhere($request);
        if ($this->defaultWhere) {
            $where = array_merge($this->defaultWhere, $where);
        }
        if ($sort_field && $sort_value) {
            $order[] = [
                'filed' => $sort_field,
                'order' => $sort_field
            ];
        }

        $query = $model->query();
        foreach ($where as $value) {
            $query->where($value[0], $value[1], $value[2]);
        }
        foreach ($orders as $order) {
            $query->orderBy($order['filed'], $order['order']);
        }
        $count = $query->count();
        $list = $query->take($limit)->skip($page)->get()->toArray();
        if ($list) {
            // 处理列表数据
            $list = $this->handleListData($list);
        }
        $data = [
            'data' => $list,
            'total' => $count
        ];

        // 文件夹
        $data['folders'] = [
            'article', 'file', 'images', 'default'
        ];
        // 文件类型
        $data['file_types'] = [
            'image' => '图片',
            'video' => '视频',
            'audio' => '音频',
            'word' => '文档',
            'other' => '其它',
        ];
        // 存储方式
        $data['storages'] = config('option.storages');
        $data['ids'] = array_column($list, 'id');

        return api_response(self::STATUS_SUCCESS, '', $data);
    }

    /**
     * 处理列表数据
     */
    protected function handleListData($data)
    {
        $className = '\\App\\Models\\' . $this->modelName;
        $model = new $className;

        $data = $model->formatDatas($data, ['format_source' => 'backend']);

        return $data;
    }

    /**
     * 筛选条件
     */
    protected function getFilterWhere($request)
    {
        $param = $request->all();
        $where = [];
        if (isset($param['folder']) && $param['folder']) {
            $where[] = ['folder', '=', $param['folder']];
        }
        if (isset($param['file_type']) && $param['file_type']) {
            $where[] = ['file_type', '=', $param['file_type']];
        }
        if (isset($param['range_date']) && $param['range_date']) {
            $rangeDate = $param['range_date'];
            $startTime = strtotime($rangeDate[0]);
            $endTime = strtotime($rangeDate[1]);
            $where[] = ['created_at', '>=', $startTime];
            $where[] = ['created_at', '<=', $endTime];
        }

        return $where;
    }

    protected function afterDelete($data)
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->modelName;
        $model = new $className;
        $delFileRes = $model->delFile($data);
        if ($delFileRes['code'] != 1) {
            return ['code' => 0, 'msg' => $delFileRes['msg']];
        }

        return parent::afterDelete($data);
    }
}
